package com.example.bbs.service.impl;

import com.example.bbs.dao.BlockDao;
import com.example.bbs.dao.PostDao;
import com.example.bbs.dao.ReplyDao;
import com.example.bbs.dao.impl.BlockDaoImpl;
import com.example.bbs.dao.impl.PostDaoImpl;
import com.example.bbs.dao.impl.ReplyDaoImpl;
import com.example.bbs.model.Post;
import com.example.bbs.model.Reply;
import com.example.bbs.service.PostService;
import com.example.bbs.utils.TimeUtil;

import java.text.ParseException;
import java.util.Date;
import java.util.List;

/**
 * @auther: zhangxin
 * @Description:
 */
public class PostServiceImpl implements PostService {

    PostDao postDao = new PostDaoImpl();
    ReplyDao replyDao = new ReplyDaoImpl();
    BlockDao blockDao= new BlockDaoImpl();
    @Override
    public List<Post> findPostByBlockId(int blockId) {
        return postDao.getPostByBlockId(blockId);
    }

    @Override
    public boolean addPost(Post post) {
        Date date = null;
        try {
           date = TimeUtil.getCurrentTimeToDate();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        post.setPostTime(date);
        post.setReplyNumber(0);
        if(postDao.addPost(post)){
           return blockDao.updateBlockPostNumber(post.getBlockId());
        }
        return true;
    }

    @Override
    public List<Post> findPostByUserId(int userId) {
        return postDao.getPostByUserId(userId);
    }

    @Override
    public boolean deletePost(Post post) {
        List<Reply> replies = replyDao.findByPostId(post.getPostId());
        for(int i = 0; i < replies.size(); i++){
            replyDao.deleteReplyById(replies.get(i).getReplyId());
        }
        return postDao.deletePostByPostId(post.getPostId());
    }

    @Override
    public boolean updatePost(Post post) {
        return postDao.updatePost(post);
    }

    @Override
    public Post getPostById(int postId) {
        return postDao.findPostById(postId);
    }
}
